<template>
  <div class="workbench">
    <ContentWrap>
      <el-form
        ref="queryFormRef"
        class="-mb-15px"
        :model="queryParams"
        :inline="false"
        label-width="130px"
      >
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="时间范围" prop="times">
              <!-- <el-date-picker
                v-model="queryParams.times"
                type="daterange"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                class="!w-240px"
              /> -->
              <div class="time-box">
                <el-date-picker
                  style="width: 220px"
                  v-model="queryParams.stime"
                  size="mini"
                  type="date"
                  :editable="false"
                  :clearable="true"
                  placeholder="开始日期"
                  :disabled-date="disableStartDate"
                />
                <span class="time-line">-</span>
                <el-date-picker
                  style="width: 220px"
                  v-model="queryParams.etime"
                  size="mini"
                  :editable="false"
                  :clearable="true"
                  type="date"
                  placeholder="结束日期"
                  :disabled-date="disableEndDate"
                />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="选择区域" prop="deptId">
              <el-tree-select
                v-model="queryParams.deptId"
                :data="deptList"
                :props="defaultProps"
                check-strictly
                node-key="id"
                placeholder="请选择区域"
              />
            </el-form-item>
          </el-col>
          <el-col :span="10" class="text-right">
            <el-form-item>
              <el-button type="primary" @click="handleQuery">查询</el-button>
              <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </ContentWrap>
    <div class="selector-box">
      <div
        class="select-item"
        v-for="item in getIntDictOptions(DICT_TYPE.DATA_SELECTOR)"
        :key="item.value"
        :class="{ active: selector.indexOf(item.value) != -1 }"
        @click="handleSelector(item.value)"
      >
        {{ item.label }}
      </div>
    </div>
    <ContentWrap>
      <div class="chart-box">
        <div id="danger_level" class="echarts-item" v-show="selector.indexOf(1) != -1"></div>
        <!-- <div id="age" class="echarts-item" v-show="selector.indexOf(2) != -1"></div> -->
        <div id="gender" class="echarts-item" v-show="selector.indexOf(3) != -1"></div>
        <div id="previous_risk" class="echarts-item" v-show="selector.indexOf(4) != -1"></div>
        <div id="current_symptoms" class="echarts-item" v-show="selector.indexOf(5) != -1"></div>
        <div id="follow_up_situation" class="echarts-item" v-show="selector.indexOf(6) != -1"></div>
        <div id="insight" class="echarts-item" v-show="selector.indexOf(7) != -1"></div>
        <!-- <div id="therapeutic_outcome" class="echarts-item" v-show="selector.indexOf(8) != -1"></div> -->
      </div>
    </ContentWrap>
  </div>
</template>

<script lang="ts" setup name="workbench">
import {
  getAgeBarOption,
  getInsightBarChartOption,
  getGenderPieChartOption,
  getRiskLevelPieChartOption,
  getCirclePieOption,
  getPreviousRiskBarOption,
  getDualHalfGaugeOption,
  getTherapeuticOutcomePieOption
} from './charts'
import * as dataAnalysisApi from '@/api/patient/dataAnalysis'
import * as DeptApi from '@/api/system/dept'
import { defaultProps, handleTree } from '@/utils/tree'
import { DICT_TYPE, getIntDictOptions, getDictLabel } from '@/utils/dict'

const echarts = getCurrentInstance()!.appContext.config.globalProperties.$echarts
const queryParams = reactive({
  stime: '',
  etime: '',
  times: [],
  deptId: '',
  dictType: ''
})
const deptList = ref<Tree[]>([]) // 树形结构
//监听stime和etime，发生变化修改times的值
watch(
  () => [queryParams.stime, queryParams.etime],
  ([newStime, newEtime]) => {
    queryParams.times = newStime && newEtime ? [newStime, newEtime] : []
  }
)
// 禁止选择晚于结束日期的开始时间
function disableStartDate(date: Date) {
  const today = new Date();

  if (queryParams.etime) {
    if (date.getTime() > new Date(queryParams.etime).getTime()) {
      return true; // 晚于结束时间
    }
  }

  if (date.getTime() > today.getTime()) {
    return true; // 晚于今天
  }

  return false;
}

// 禁止选择早于开始日期的结束时间
function disableEndDate(date: Date) {
   const today = new Date();

  if (queryParams.stime) {
    const stime = new Date(queryParams.stime);

    if (date.getTime() < stime.getTime()) {
      return true; // 早于开始时间
    }

    const maxEnd = new Date(stime);
    maxEnd.setFullYear(maxEnd.getFullYear() + 1); // 开始时间 + 1 年

    if (date.getTime() > maxEnd.getTime()) {
      return true; // 跨度超 1 年
    }
  }

  if (date.getTime() > today.getTime()) {
    return true; // 晚于今天
  }

  return false;
}
const initDeptTree = async () => {
  // 加载部门树
  deptList.value = handleTree(await DeptApi.getSimpleDeptList())
}
const queryFormRef = ref() // 搜索的表单
/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.stime = ''
  queryParams.etime = ''
  queryFormRef.value.resetFields()
  handleQuery()
}
/** 查询按钮操作 */
const handleQuery = () => {
  getData(selector)
}

const initAgeBar = async () => {
  const xAxisData = ['0~10岁', '11~20岁', '21~30岁', '31~40岁', '41~50岁', '51~60岁', '60+岁']
  const seriesData = [
    {
      measureUnit: '人',
      value: 500
    },
    {
      measureUnit: '人',
      value: 800
    },
    { measureUnit: '人', value: 400 },
    { measureUnit: '人', value: 300 },
    { measureUnit: '人', value: 400 },
    { measureUnit: '人', value: 400 },
    { measureUnit: '人', value: 400 }
  ]

  // const data = await BigScreenApi.getHighRiskPatients(timeParams.value)
  // data?.forEach((element) => {
  //   xAxisData.push(element.month)
  //   seriesData.push(element.count)
  // })
  const ageBarChart = document.getElementById('age')
  if (ageBarChart) {
    const option = getAgeBarOption(xAxisData, seriesData)
    const ageBarChartInstance = echarts.init(ageBarChart)
    ageBarChartInstance.setOption(option)
    window.addEventListener('resize', () => {
      ageBarChartInstance.resize()
    })
  }
}

const initInsightBar = async () => {
  queryParams.dictType = 'insight'
  const dictOptions = getIntDictOptions(DICT_TYPE.INSIGHT)
  const xAxisData = []
  const seriesData = []

  // 先从字典中获取所有可能的值
  dictOptions.forEach((dict) => {
    xAxisData.push(dict.label)
  })

  // 设置默认值为0
  xAxisData.forEach(() => {
    seriesData.push(0)
  })

  const data = await dataAnalysisApi.getSubDbStatusStats(queryParams)

  // 用接口返回的数据更新seriesData
  data?.typeCounts?.forEach((element) => {
    const index = dictOptions.findIndex((item) => String(item.value) === String(element.type))
    if (index !== -1) {
      seriesData[index] = element.count
    }
  })

  const insightBarChart = document.getElementById('insight')
  if (insightBarChart) {
    const option = getInsightBarChartOption(xAxisData, seriesData)
    const insightBarChartInstance = echarts.init(insightBarChart)
    insightBarChartInstance.setOption(option)
    window.addEventListener('resize', () => {
      insightBarChartInstance.resize()
    })
  }
}

const initGenderPie = async () => {
  queryParams.dictType = 'gender'
  const dictOptions = getIntDictOptions(DICT_TYPE.GENDER)

  // 构建数据结构，包含初始默认值
  let normaldata = dictOptions.map((dict, index) => {
    const colors = ['#E6BB2B', '#E05541', '#69C0FF', '#95DE64']
    return {
      zbPercentValue: 0,
      zbTitle: '指标值',
      name: dict.label,
      Attributes: {
        MAINDIMMEMBER_NAMECOLUMN: dict.label,
        MAINDIMMEMBER_KEYCOLUMN: 'KEY_' + index,
        MAINDIM_NAMECOLUMN: 'zbTitle',
        MAINDIM_KEYCOLUMN: 'zbName',
        C_ZBNAME: 'zbValue',
        DRILL_DOWN: 'false'
      },
      itemStyle: {
        color: colors[index % colors.length]
      },
      label: {
        color: colors[index % colors.length]
      },
      value: 0
    }
  })

  const data = await dataAnalysisApi.getTypeSummary(queryParams)

  // 用接口返回的数据更新value
  if (data && data.typeCounts) {
    data.typeCounts.forEach((element) => {
      const index = dictOptions.findIndex((item) => String(item.value) === String(element.type))
      if (index !== -1) {
        normaldata[index].value = element.count
      }
    })
  }

  const genderPieChart = document.getElementById('gender')
  if (genderPieChart) {
    const option = getGenderPieChartOption(normaldata)
    const genderPieChartInstance = echarts.init(genderPieChart)
    genderPieChartInstance.setOption(option)
    window.addEventListener('resize', () => {
      genderPieChartInstance.resize()
    })
  }
}

const initRiskLevelPie = async () => {
  queryParams.dictType = 'risk_assessment'
  const dictOptions = getIntDictOptions(DICT_TYPE.RISK_ASSESSMENT)

  // 初始化数据，为每个级别设置默认值0
  const trafficWay = dictOptions.map((dict) => ({
    name: dict.label,
    value: 0
  }))

  const data = await dataAnalysisApi.getTypeSummary(queryParams)

  // 用接口返回的数据更新value
  if (data && data.typeCounts) {
    data.typeCounts.forEach((element) => {
      const index = dictOptions.findIndex((item) => String(item.value) === String(element.type))
      if (index !== -1) {
        trafficWay[index].value = element.count
      }
    })
  }
  // 处理需要的数组
  const Xdata = trafficWay.map((item) => item.name)
  const TS_val = trafficWay.map((item) => item.value)

  const riskLevelPieChart = document.getElementById('danger_level')
  if (riskLevelPieChart) {
    const option = getRiskLevelPieChartOption(Xdata, TS_val)
    const riskLevelPieChartInstance = echarts.init(riskLevelPieChart)
    riskLevelPieChartInstance.setOption(option)
    window.addEventListener('resize', () => {
      riskLevelPieChartInstance.resize()
    })
  }
}

const initPreviousRiskBar = async () => {
  const data = await dataAnalysisApi.getDangerBehaviorStats(queryParams)
  const information = {
    color: '#069DFD',
    area: ['轻度滋事', '肇事', '肇祸', '其他危险行为'],
    dataArray: [
      data?.minorNuisanceCount || 0,
      data?.incidentCount || 0,
      data?.harmfulIncidentCount || 0,
      data?.otherDangerousBehaviorCount || 0
    ]
  }
  const previousRiskBarChart = document.getElementById('previous_risk')
  if (previousRiskBarChart) {
    const option = getPreviousRiskBarOption(information)
    const previousRiskBarChartInstance = echarts.init(previousRiskBarChart)
    previousRiskBarChartInstance.setOption(option)
    window.addEventListener('resize', () => {
      previousRiskBarChartInstance.resize()
    })
  }
}

const initFollowUpSituationPie = async () => {
  queryParams.dictType = 'sub_library_status'
  const data = await dataAnalysisApi.getSubDbStatusStats(queryParams)
  const dictOptions = getIntDictOptions(DICT_TYPE.SUB_LIBRARY_STATUS)
  // 初始化数据，为每个状态设置默认值0
  let status = dictOptions.map((dict) => ({
    name: dict.label,
    value: 0
  }))
  // 用接口返回的数据更新value
  if (data && data.typeCounts) {
    data.typeCounts.forEach((element) => {
      const index = dictOptions.findIndex((item) => String(item.value) === String(element.type))
      if (index !== -1) {
        status[index].value = element.count
      }
    })
  }

  const followUpSituationPieChart = document.getElementById('follow_up_situation')
  if (followUpSituationPieChart) {
    const option = getDualHalfGaugeOption(status)
    const followUpSituationPieChartInstance = echarts.init(followUpSituationPieChart)
    followUpSituationPieChartInstance.setOption(option)
    window.addEventListener('resize', () => {
      followUpSituationPieChartInstance.resize()
    })
  }
}

const initTherapeuticOutcomePie = async () => {
  const dictOptions = getIntDictOptions(DICT_TYPE.THERAPEUTIC_OUTCOME)

  // 初始化数据，为每个状态设置默认值0
  const resultData = dictOptions.map((dict) => ({
    name: dict.label,
    value: 0
  }))

  // 如果有需要可以添加对应的API调用
  // const data = await dataAnalysisApi.getTherapeuticOutcomeStats(queryParams)
  // if (data && data.typeCounts) {
  //   data.typeCounts.forEach((element) => {
  //     const index = dictOptions.findIndex(item => String(item.value) === String(element.type))
  //     if (index !== -1) {
  //       resultData[index].value = element.count
  //     }
  //   })
  // }

  const therapeuticOutcomePieChart = document.getElementById('therapeutic_outcome')
  if (therapeuticOutcomePieChart) {
    const option = getTherapeuticOutcomePieOption(resultData)
    const therapeuticOutcomePieChartInstance = echarts.init(therapeuticOutcomePieChart)
    therapeuticOutcomePieChartInstance.setOption(option)
    window.addEventListener('resize', () => {
      therapeuticOutcomePieChartInstance.resize()
    })
  }
}

let currentSymptomsChartInstance = null
const initCurrentSymptomsPie = async () => {
  queryParams.dictType = 'symptoms'
  const dictOptions = getIntDictOptions(DICT_TYPE.SYMPTOMS)
  const resultData = dictOptions.map((dict) => ({
    name: dict.label,
    value: 0
  }))
  const data = await dataAnalysisApi.getSubDbStatusStats(queryParams)
  // 用接口返回的数据更新seriesData
  data?.typeCounts?.forEach((element) => {
    const index = dictOptions.findIndex((item) => String(item.value) === String(element.type))
    if (index !== -1) {
      resultData[index].value = element.count
    }
  })
  // 处理需要的数组
  const label = resultData.map((item) => item.name)
  const value = resultData.map((item) => item.value)
  const currentSymptomsChart = document.getElementById('current_symptoms')
  if (currentSymptomsChart) {
    const { getOption, startMove, stopMove } = getCirclePieOption({ label, value })
    // 销毁之前的实例
    if (currentSymptomsChartInstance) {
      currentSymptomsChartInstance.dispose()
    }
    currentSymptomsChartInstance = echarts.init(currentSymptomsChart)
    currentSymptomsChartInstance.setOption(getOption())
    startMove(currentSymptomsChartInstance)
    window.addEventListener('resize', () => {
      currentSymptomsChartInstance.resize()
    })
  }
}

// const initCurrentSymptomsTree = async () => {
//   queryParams.dictType = 'symptoms'
//   const dictOptions = getIntDictOptions(DICT_TYPE.SYMPTOMS)

//   // 颜色配置列表，可重复使用
//   const colorConfigs = [
//     {
//       type: 'linear',
//       x: 0, y: 1, x2: 1, y2: 0,
//       colorStops: [
//         { offset: 0, color: '#245547' },
//         { offset: 1, color: '#3BD3A8' }
//       ],
//       globalCoord: false
//     },
//     {
//       type: 'linear',
//       x: 0, y: 1, x2: 1, y2: 0,
//       colorStops: [
//         { offset: 0, color: '#515B37' },
//         { offset: 1, color: '#B4D16A' }
//       ],
//       globalCoord: false
//     },
//     {
//       type: 'linear',
//       x: 0, y: 1, x2: 1, y2: 0,
//       colorStops: [
//         { offset: 0, color: '#254C5A' },
//         { offset: 1, color: '#3AACD2' }
//       ],
//       globalCoord: false
//     },
//     {
//       type: 'linear',
//       x: 0, y: 1, x2: 1, y2: 0,
//       colorStops: [
//         { offset: 0, color: '#346041' },
//         { offset: 1, color: '#67D171' }
//       ],
//       globalCoord: false
//     },
//     {
//       type: 'linear',
//       x: 0, y: 1, x2: 1, y2: 0,
//       colorStops: [
//         { offset: 0, color: '#584732' },
//         { offset: 1, color: '#C5914D' }
//       ],
//       globalCoord: false
//     },
//     {
//       type: 'linear',
//       x: 0, y: 1, x2: 1, y2: 0,
//       colorStops: [
//         { offset: 0, color: '#2F545F' },
//         { offset: 1, color: '#68CED3' }
//       ],
//       globalCoord: false
//     },
//     {
//       type: 'linear',
//       x: 0, y: 1, x2: 1, y2: 0,
//       colorStops: [
//         { offset: 0, color: '#2F3F5E' },
//         { offset: 1, color: '#688DD3' }
//       ],
//       globalCoord: false
//     },
//     {
//       type: 'linear',
//       x: 0, y: 1, x2: 1, y2: 0,
//       colorStops: [
//         { offset: 0, color: '#30325F' },
//         { offset: 1, color: '#6C68D3' }
//       ],
//       globalCoord: false
//     }
//   ]

//   // 初始化树形图数据
//   const treeData = dictOptions.map((dict, index) => ({
//     name: dict.label,
//     itemStyle: {
//       color: colorConfigs[index % colorConfigs.length]
//     },
//     value: 0
//   }))

//   const data = await dataAnalysisApi.getSubDbStatusStats(queryParams)

//   // 用接口返回的数据更新value
//   if (data) {
//     data?.typeCounts?.forEach((element) => {
//       const index = dictOptions.findIndex(item => String(item.value) === String(element.type))
//       if (index !== -1) {
//         treeData[index].value = element.count
//       }
//     })
//   }

//   const currentSymptomsChart = document.getElementById('current_symptoms')
//   if (currentSymptomsChart) {
//     const option = getTreemapOption(treeData)
//     const currentSymptomsChartInstance = echarts.init(currentSymptomsChart)
//     currentSymptomsChartInstance.setOption(option)
//     window.addEventListener('resize', () => {
//       currentSymptomsChartInstance.resize()
//     })
//   }
// }

const selector = ref([])
//选择指标后逻辑
const handleSelector = (val: any) => {
  // 如果 selector 中不存在 val，则将其添加；否则，将其移除
  const index = selector.value.indexOf(val)
  if (index === -1) {
    selector.value.push(val)
    //获取数据
    getData(selector)
  } else {
    selector.value.splice(index, 1)
  }
}
//选择指标后逻辑
const getData = (selector: any) => {
  // 根据 selector 中的值调用对应的初始化方法
  if (selector.value.includes(1)) {
    initRiskLevelPie()
  }
  if (selector.value.includes(2)) {
    initAgeBar()
  }
  if (selector.value.includes(3)) {
    initGenderPie()
  }
  if (selector.value.includes(4)) {
    initPreviousRiskBar()
  }
  if (selector.value.includes(5)) {
    initCurrentSymptomsPie()
  }
  if (selector.value.includes(6)) {
    initFollowUpSituationPie()
  }
  if (selector.value.includes(7)) {
    initInsightBar()
  }
  if (selector.value.includes(8)) {
    initTherapeuticOutcomePie()
  }
}
onMounted(() => {
  initDeptTree()
  // initAgeBar()
  // initInsightBar()
  // initFollowUpSituationPie()
  // initTherapeuticOutcomePie()
  // initCurrentSymptomsPie()
  // initPreviousRiskBar()
  // initRiskLevelPie()
  // initGenderPie()
})
</script>

<style lang="scss" scoped>
.text-right {
  display: flex;
  justify-content: flex-end;
}
.chart-box {
  width: 100%;
  height: 600px;
  display: grid;
  grid-auto-rows: 295px;
  grid-template-columns: repeat(3, 1fr);
  flex: 1;
  gap: 10px;
}
.echarts-item {
  width: 520px;
  height: 295px;
  background: linear-gradient(to bottom, #fcfcfc, #f5f9ff);
  border-radius: 12px;
  box-shadow: 0 3px 15px rgba(83, 109, 254, 0.08);
  transition: all 0.3s ease;
  border: 1px solid #eef2f9;
  position: relative;
  overflow: hidden;
}

.echarts-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 25px rgba(83, 109, 254, 0.12);
}
.selector-box {
  width: 100%;
  height: 60px;
  display: grid;
  grid-auto-rows: 50px;
  grid-template-columns: repeat(6, 1fr);
  flex: 1;
  gap: 9px;
}
.select-item {
  width: 272px;
  height: 50px;
  font-family: Microsoft YaHei;
  font-weight: 500;
  font-size: 16px;
  color: #536dfe;
  background-color: #f5f7ff;
  border-radius: 10px;
  border: 1px solid #e0e6f1;

  cursor: pointer;
  text-align: center;
  line-height: 47px;
  transition: all 0.3s ease;
  box-shadow: 0 2px 6px rgba(83, 109, 254, 0.05);
  position: relative;
}
// 鼠标移入，放大1.05
.select-item:hover {
  transform: scale(1.05);
  transition: all 0.3s ease;
  background-color: #eef1ff;
}

//点击选中状态，蓝色背景，
.active {
  background: linear-gradient(135deg, #536dfe, #8c9eff);
  border-color: transparent;

  font-family: Microsoft YaHei;
  font-weight: 500;
  font-size: 16px;
  color: #ffffff;
  box-shadow: 0 5px 15px rgba(83, 109, 254, 0.25);
  transition: all 0.3s ease;
}

@media screen and (max-width: 1600px) {
  .chart-box {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media screen and (max-width: 1200px) {
  .chart-box {
    grid-template-columns: repeat(1, 1fr);
  }
}
.time-box {
  display: flex;
  gap: 5px;
}
</style>
